<script setup lang="ts">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref } from 'vue'
import { required } from '@/utils/formRules'
import { ElInput } from 'element-plus'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const userInfo: any = wsCache.get('userInfo')
const data = ref<any>({})
// import { Uploads, UploadFiles } from '@/components/Uploads'
import { UploadFileLxq } from '@/components/UploadFileLxq'
import { UploadLxq } from '@/components/UploadLxq'
const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  }
})
const typeChange = (value) => {
  data.value.file_type = value
  if (data.value.file_name) {
    data.value.file_url = ''
    data.value.file_name = ''
  }
}

const onChange = (value) => {
  const { setValues } = methods
  data.value.file_name = value.file_name
  data.value.fileData = value
  data.value.file_size = value.file_size
  setValues(data.value)
}

const schema: any = [
  {
    field: 'customer_name',
    component: 'Input',
    label: '所属牧场',
    componentProps: {
      readonly: true
    }
  },
  {
    field: 'file_type',
    label: '文件类型',
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '图片',
          value: '1'
        },
        {
          label: '文件',
          value: '2'
        }
      ],
      onChange: typeChange
    }
  },
  {
    field: 'file',
    label: '上传文件'
  },
  {
    field: 'file_name',
    label: '文件名称',
    component: 'Input'
  },
  {
    field: 'file_title',
    label: '文件标题',
    component: 'Input'
  },
  {
    field: 'file_size',
    label: '文件大小',
    component: 'Input',
    componentProps: {
      disabled: true
    }
  }
]
const rules = reactive({
  file_title: [required],
  file_name: [required],
  file_type: [required]
})

const { register, methods, elFormRef } = useForm({
  schema
})

watch(
  () => props.currentRow,
  (currentRow) => {
    console.log(currentRow, 'currentRow')
    if (!currentRow) return
    currentRow.customer_name = userInfo.default_org_name
    currentRow.customer_id = userInfo.default_org_id
    const { setValues } = methods
    if (props.currentRow && props.currentRow.id) {
      data.value = {}
    }
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  elFormRef,
  getFormData: methods.getFormData
  // fileData,
  // file_name
})
</script>

<template>
  <Form :rules="rules" @register="register" :data="data">
    <template #file>
      <UploadLxq v-if="data.file_type == 1" @change="onChange" v-model="data.file_url" />
      <UploadFileLxq @change="onChange" v-else v-model="data.file_url" />
    </template>
    <!-- <template #file_name>
      <ElInput v-model="file_name" />
    </template> -->
    <template #file_size>
      <ElInput v-model="data.file_size" />
    </template>
  </Form>
</template>
